<template>
  <div class="user-container">
    <el-row class="usernav">
      <el-col :span="5">
        角色名称：
        <el-input placeholder="请输入角色名称" v-model="listQuery.title" class="input-with-select" style='width: 60%'>
          <el-button slot="append" icon="el-icon-search" @click="handleFilter" v-model="listQuery.title"></el-button>
        </el-input>
      </el-col>
      <!-- box弹窗 -->
      <el-button type="primary" @click="handleAdd">添加角色</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出Excel
      </el-button>
      <el-dialog
        :before-close="close"
        :title="dialogStatus"
        :visible.sync="dialogVisible"
        width="30%">
        <el-form  ref="formData" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色说明">
            <el-input type="textarea" v-model="ruleForm.title" placeholder="请输入角色说明"></el-input>
          </el-form-item>
          <el-form-item label="是否设置权限">
            <el-select v-model="ruleForm.status" placeholder="请选择">
              <el-option label="设置权限" value="1"></el-option>
              <el-option label="不设置权限" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogStatus==='添加角色'? handleadd(): handleedit()">提 交</el-button>
        </span>
      </el-dialog>
    </el-row>
    <el-table
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
      align="center"
      prop="name"
      label="角色名称"
      width="500">
      </el-table-column>
      <el-table-column
      align="center"
      prop="title"
      label="角色说明"
      width="600">
      </el-table-column>
      <el-table-column
      align="center"
      prop="status"
      label="是否已设置权限">
      <template slot-scope="{row}">
        <span v-if="row.status=='1'" style="color: green">已设置</span>
        <span v-else style="color: red">未设置</span>
      </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="row">
          <el-button size="mini" type="warning" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handledel(row)">删除</el-button>
          <el-button size="mini" type="success">角色功能</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
         <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { usetList, userAdd, userEdit, userDel } from '@/api/user-article' // 请求api
import Pagination from '@/components/Pagination' // 分页组件
export default {
  name: 'UserManagement',
  components: { Pagination },
  data() {
    return {
      tableData: null, // 
      total: 0, // 数据条数
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined
      },
      dialogStatus: '', // 弹出框类型 
      dialogVisible: false,
      downloadLoading: false,
      ruleForm: {
        name: '',
        title: '',
        status: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, message: '角色名称至少 3 字符', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getList()
  },

  methods: {
    // 获取数据
    getList() {
      usetList(this.listQuery).then(response => {
        this.tableData = response.data.items
        this.total = response.data.total
        console.log(response.data)
      })
    },
    // 搜索按钮
    handleFilter() {
      this.listQuery.total = 1
      this.getList()
    },
    // 添加角色按钮
    handleAdd() {
      this.ruleForm = {
        name: '',
        title: '',
        status: ''
      },
      this.dialogStatus = '添加角色'
      this.dialogVisible = true
    },
    // 确定添加角色按钮
    handleadd() {
      this.$refs['formData'].validate((valid) => { 
        if(valid){
          userAdd(this.ruleForm).then(() => {
          this.tableData.unshift(this.ruleForm)
          })
          this.dialogVisible=false
          this.$refs['formData'].clearValidate()
          this.$notify({
            title: '温馨提示',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
        }
      })
      
    },
    // 关闭角色对话框
    close() {
      this.dialogVisible=false
      this.$nextTick(() => {
        this.ruleForm = {
          name: '',
          Account: '',
          status: ''
        }
        this.$refs['formData'].clearValidate()
      })
    },
    // 编辑控件
    handleEdit(slot) {
      this.ruleForm = Object.assign({}, slot.row) // 拷贝到ruleForm上
      this.dialogStatus = '编辑角色'
      this.dialogVisible = true
      console.log(this.ruleForm);
    },
    // 确定编辑角色按钮
    handleedit() {
      this.$refs['formData'].validate((valid) => { 
        if(valid){ // 如果校验规则通过
          userEdit(this.ruleForm).then(() => {
            const index = this.tableData.findIndex(itme => itme.id === this.ruleForm.id)
              this.tableData.splice(index, 1, this.ruleForm)
          })
          this.dialogVisible=false
          this.$refs['formData'].clearValidate()
          this.$notify({
            title: '温馨提示',
            message: '编辑成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 删除控件
    handledel(slot) {
      this.tableData.splice(slot.$index,1)
      this.$notify({
        title: '温馨提示',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
    },
    // 导出excel
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['角色名称', '角色说明', '是否已设置权限', '操作'] // 表头
        const filterVal = ['name', 'title', 'status'] // 内容
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.tableData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style scoped lang='scss'>
  .user-container {
    margin: 20px;
    // display: flex;
    .usernav {
      margin-bottom: 10px;
      ::v-deep .el-dialog {
        border-radius: 5px;
        .el-dialog__header {
          background-color:steelblue;
          .el-dialog__title {
            color: #fff;
          }
        }
      }
    }
  }
</style>
